package service.impl.graph;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import model.GraphResult;
import model.GraphSearchCriteria;

import org.json.simple.JSONArray;

import service.impl.Converter;
import service.impl.JSONEncoder;

public class WeekGraphConstructor {

	public static JSONArray constructWeekGraph(List<GraphResult> graphResults, GraphSearchCriteria criteria) {
		Map<Integer, Double> averageByDay = new HashMap<Integer, Double>();
		classifyByDayOfWeek(averageByDay, graphResults);
		return JSONEncoder.encodeWeekGraphData(averageByDay);
	}

	private static void classifyByDayOfWeek(Map<Integer, Double> averageByDay, List<GraphResult> graphResults) {
		Map<Integer, Integer> sumOfAnswersInDay = new HashMap<Integer, Integer>();
		populateWithAllDaysOfWeek(averageByDay, sumOfAnswersInDay);
		for (GraphResult result : graphResults) {
			int dayOfWeek = result.getAnswerDayOfWeek();
			Double studyTime = result.getStudyPeriod();
			Double studyTimeSum = averageByDay.get(dayOfWeek) + studyTime;
			averageByDay.put(dayOfWeek, studyTimeSum);
			sumOfAnswersInDay.put(dayOfWeek, sumOfAnswersInDay.get(dayOfWeek) + 1);
		}
		// Just divide by needed number to get average
		for (Integer dayOfWeek : averageByDay.keySet()) {
			Integer divider = sumOfAnswersInDay.get(dayOfWeek);
			if (divider.equals(0) || divider.equals(1)) {
				continue;
			}
			Double studyTimeSum = averageByDay.get(dayOfWeek);
			averageByDay.put(dayOfWeek, Converter.formatDouble(studyTimeSum / divider, 2));
		}
	}

	private static void populateWithAllDaysOfWeek(Map<Integer, Double> averageByDay, Map<Integer, Integer> sumOfAnswersInDay) {
		for (int i = 1; i <= 7; i++) {
			averageByDay.put(i, 0.0);
			sumOfAnswersInDay.put(i, 0);
		}
	}

}
